package com.mogu.blogs.controller;

import com.mogu.blogs.service.BlogContentService;
import com.mogu.entity.TBlog;
import com.mogu.message.SysConf;
import com.mogu.utils.ResultUtil;
import com.mogu.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author muxiaofeng
 * @Date 2020/6/10 19:22.
 */
@RestController
@RequestMapping("/content")
public class BlogContentController {

    @Autowired
    BlogContentService blogContentService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/getBlogByUid")
    public String getBlogByUid(@RequestParam String uid){

        if (StringUtils.isEmpty(uid)){
            return ResultUtil.result(SysConf.ERROR,"uid不能为空");
        }

        TBlog tBlog = blogContentService.getBlogByUid(uid);

        if (tBlog == null || tBlog.getStatus() == "0" || tBlog.getIsPublish() == "0"){
            return ResultUtil.result("400","该文章已下架或被删除");
        }

        if (tBlog != null){
            String jsonResult = stringRedisTemplate.opsForValue().get(uid);

            if (StringUtils.isEmpty(jsonResult)){

                Integer clickCount = tBlog.getClickCount() + 1;
                tBlog.setClickCount(clickCount);
                //tBlog.updateById();

                stringRedisTemplate.opsForValue().set(uid,tBlog.getClickCount().toString(),24, TimeUnit.HOURS);
            }
        }

        return ResultUtil.result(SysConf.SUCCESS,tBlog);
    }

    @RequestMapping("/getBlogPraiseCountByUid")
    public String getBlogPraiseCountByUid(@RequestParam String uid){

        return ResultUtil.result(SysConf.SUCCESS,blogContentService.getBlogPraiseCountByUid(uid));
    }

    @RequestMapping("/praiseBlogByUid")
    public String praiseBlogByUid(@RequestParam String uid){

        return blogContentService.praiseBlogByUid(uid);
    }
}
